package com.example.psychologicalappointmentsystem.tools;

import com.example.psychologicalappointmentsystem.Enum.UploadFileType;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * ClassName FileUploadUtil
 * Description TODO 处理文件上传的操作
 * Date 2025/2/13 10:49
 * Version 1.0
 */
public class FileUploadUtil {

    private static final String HEADIMAGE_DIR = "headImage/";

    public static String saveFile(MultipartFile file, UploadFileType uploadFileType) throws IOException {

        String UPLOAD_DIR = "uploads/";

        switch (uploadFileType){
            case HEADIMAGE:
                UPLOAD_DIR += HEADIMAGE_DIR;
                break;
        }

        // 确保上传目录存在
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一的文件名
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        Path filePath = Paths.get(UPLOAD_DIR + fileName);

        // 保存文件到本地
        Files.copy(file.getInputStream(), filePath);

        // 返回文件的相对路径
        return UPLOAD_DIR + fileName;
    }
}
